package com.mallcai.bigdata.ladon.controller.common;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mallcai.bigdata.ladon.controller.common.form.DataSourceForm;
import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.dpl.vo.DatasourceType;
import com.mallcai.bigdata.ladon.service.common.IDatasourceService;
import com.mallcai.bigdata.ladon.vo.ColumnVo;
import com.mallcai.bigdata.ladon.vo.MyPageInfo;
import com.mallcai.bigdata.ladon.vo.TableVo;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by oneape<oneape15@163.com>
 * Created 2019-05-22 10:27.
 * Modify:
 */
@RestController
@RequestMapping("/common/datasource")
public class DatasourceController {

    @Autowired
    private IDatasourceService iDatasourceService;

    @RequestMapping("/add")
    public String addDatasource(@RequestBody @Validated(value = DataSourceForm.AddCheck.class) DataSourceForm form) {
        Datasource ds = form.toEntity();
        int status = iDatasourceService.addDatasource(ds);
        if (status > 0) {
            return "添加数据源成功";
        } else {
            throw new BusinessException("添加数据源失败");
        }
    }

    @RequestMapping("/edit")
    public String editDatasource(@RequestBody @Validated(value = DataSourceForm.EditCheck.class) DataSourceForm form) {
        Datasource ds = form.toEntity();
        int status = iDatasourceService.editDatasource(ds);
        if (status > 0) {
            return "修改数据源成功";
        } else {
            throw new BusinessException("修改数据源失败");
        }
    }

    @RequestMapping("/test")
    public String testConnection(@RequestBody @Validated(value = DataSourceForm.AddCheck.class) DataSourceForm form) {
        Datasource ds = form.toEntity();
        boolean success = iDatasourceService.test(ds);
        if (success) {
            return "数据库连接测试成功";
        } else {
            throw new BusinessException("数据库连接测试失败");
        }
    }


    @RequestMapping("/del")
    public String delDatasource(@RequestBody @Validated(value = DataSourceForm.IdCheck.class) DataSourceForm form) {
        Datasource ds = form.toEntity();
        int status = iDatasourceService.deleteDatasource(ds);
        if (status > 0) {
            return "数据库连接测试成功";
        } else {
            throw new BusinessException("数据库连接测试失败");
        }
    }

    @RequestMapping("/getById")
    public Datasource getById(@RequestBody @Validated(value = DataSourceForm.IdCheck.class) DataSourceForm form) {
        return iDatasourceService.getById(form.getDsId());
    }

    @RequestMapping("/getByPage")
    public MyPageInfo getByPage(@RequestBody @Validated DataSourceForm form) {
        PageHelper.startPage(form.getCurrentPage(), form.getPageSize());
        List<Datasource> datasources = iDatasourceService.getByParams(form.getParams());
        PageInfo<Datasource> pageInfo = new PageInfo<>(datasources);
        return new MyPageInfo<>(pageInfo);
    }

    @RequestMapping("/changeStatus")
    public String changeStatus(@RequestBody @Validated(value = DataSourceForm.ChangeStatusCheck.class) DataSourceForm form) {
        Datasource ds = form.toEntity();

        boolean isUsing = iDatasourceService.isUsing(ds.getId());
        if (isUsing) {
            throw new BusinessException("数据源正在使用不能被停用");
        }
        int status = iDatasourceService.editDatasource(ds);
        if (status > 0) {
            return "更改数据源状态成功";
        } else {
            throw new BusinessException("更改数据源状态失败");
        }
    }

    /**
     * 获取所有数据源的基本信息
     *
     * @param form DatasourceForm
     * @return List
     */
    @RequestMapping("/getAllSimple")
    public List<Map<String, Object>> getAll(@RequestBody @Validated DataSourceForm form) {
        Map<String, Object> params = form.getParams();
        if (params == null) {
            params = new HashMap<>();
        }
        // 只查询出可用的
        if (!params.containsKey("status")) {
            params.put("status", 0);
        }

        List<Datasource> datasources = iDatasourceService.getByParams(params);

        List<Map<String, Object>> list = new ArrayList<>();
        if (datasources != null && datasources.size() > 0) {
            for (Datasource db : datasources) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", db.getId());
                map.put("name", db.getName());
                map.put("type", db.getType());
                map.put("useType", db.getUseType());
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 根据数据源id 获取包括的所有表信息
     *
     * @param form DataSourceForm
     * @return List
     */
    @RequestMapping("/getTables")
    public List<TableVo> getTables(@RequestBody @Validated(value = DataSourceForm.IdCheck.class) DataSourceForm form) {
        List<TableVo> tables = iDatasourceService.getAllTables(form.getDsId());
        if (tables == null) {
            tables = new ArrayList<>();
        }
        return tables;
    }

    /**
     * 获取所有数据类型
     *
     * @return ApiResult
     */
    @RequestMapping("/getDataTypes")
    public List<String> getDataTypes() {
        List<String> dataTypes = new ArrayList<>();

        for (DataType dt : DataType.values()) {
            dataTypes.add(dt.getCode());
        }

        return dataTypes;
    }

    /**
     * 获取支持的数据源类型
     *
     * @return ApiResult
     */
    @RequestMapping("/getAllDsTypes")
    public List<Map<String, String>> getAllDsTypes() {
        List<Map<String, String>> list = new ArrayList<>();
        for (DatasourceType dt : DatasourceType.values()) {
            Map<String, String> map = new HashMap<>();
            map.put("type", dt.getCode());
            map.put("driver", dt.getDriver());
            list.add(map);
        }
        return list;
    }

    /**
     * 根据数据源id 获取包括的所有表及其字段信息
     *
     * @param form DataSourceForm
     * @return List
     */
    @RequestMapping("/getTablesAndColumns")
    public List getTablesAndColumns(@RequestBody @Validated(value = DataSourceForm.IdCheck.class) DataSourceForm form) {
        List<Pair<String, List<String>>> pairs = new ArrayList<>();
        List<TableVo> tables = iDatasourceService.getAllTables(form .getDsId());
        if (tables == null) {
            return new ArrayList<>();
        }
        for(TableVo table:tables) {
            List<ColumnVo> columnVos=iDatasourceService.getTableColumns(form.getDsId(),table.getName());
            List<String> columnNames=new ArrayList<>();
            if(columnVos!=null) {
                for(ColumnVo columnVo:columnVos) {
                    columnNames.add(columnVo.getName());
                }
            }
            pairs.add(new MutablePair<>(table.getName(),columnNames));
        }
        return pairs;
    }
}
